<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { getMenuTreeList } from '../../api/miniMenu'
import { getRoleMiniMenuList } from '../../api/roles'

interface Props {
  roleId: string | null
}

const props = defineProps<Props>()

const loading = ref(false)

const treeRef = ref()
const tree = ref<any>([])
const checkStrictlyFlg = ref(true)
const checkKeys = ref<any>([])

const typeArr = ['功能模块', '功能菜单', '功能按钮']

const getCheckKeys = () => {
  getRoleMiniMenuList({ roleId: props.roleId })
    .then((res: any) => {
      checkKeys.value = res.map((item: any) => item.menuId)
      nextTick(() => {
        checkStrictlyFlg.value = false
      })
    })
    .finally(() => {
      loading.value = false
    })
}

const getMenuTree = () => {
  loading.value = true
  getMenuTreeList({ useStatus: '1' })
    .then((res: any) => {
      tree.value = res
      getCheckKeys()
    })
    .catch(() => {
      loading.value = false
    })
}
getMenuTree()

const submitForm = () => {
  const checkedNodes = treeRef.value.getCheckedNodes(false, true)
  const result = checkedNodes.map((item: any) => {
    return item.menuId
  })
  return result
}

defineExpose({
  submitForm
})
</script>

<template>
  <div v-loading="loading" class="tree-warpper">
    <el-tree
      ref="treeRef"
      :default-checked-keys="checkKeys"
      :data="tree"
      show-checkbox
      default-expand-all
      :expand-on-click-node="false"
      node-key="menuId"
      :check-strictly="checkStrictlyFlg"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ data.miniMenuName }} - {{ typeArr[parseInt(data.miniMenuType)] }}</span>
          <span v-show="false">{{ node.label }}</span>
        </span>
      </template>
    </el-tree>
  </div>
</template>

<style lang="scss" scoped>
.tree-warpper {
  min-height: 100%;
}
</style>
